import { useRef, useEffect, createContext, useContext, useState } from "react";
import { fabric } from "fabric";
import { FloatButton, Modal, Input } from "antd";
import {
  UpOutlined,
  SaveOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  ClearOutlined,
  FontSizeOutlined,
} from "@ant-design/icons";

const fcContext = createContext();
function useFabricCanvas(name) {
  const CanvasRef = useRef(null);
  const fabricCanvas = useRef(null);
  const initialized = useRef(false);

  //等待canvs DOM渲染完成，初始化fabric
  useEffect(() => {
    if (CanvasRef.current && !initialized.current) {
      console.log("canvas created");

      initialized.current = true;
      fabricCanvas.current = new fabric.Canvas(name, {
        backgroundColor: "#F2F3F5",
      });

      //缩放
      fabricCanvas.current.on("mouse:wheel", function (opt) {
        var delta = opt.e.deltaY;
        var zoom = fabricCanvas.current.getZoom();
        zoom *= 0.999 ** delta;
        if (zoom > 20) zoom = 20;
        if (zoom < 0.01) zoom = 0.01;
        fabricCanvas.current.zoomToPoint(
          { x: opt.e.offsetX, y: opt.e.offsetY },
          zoom
        );
        opt.e.preventDefault();
        opt.e.stopPropagation();
      });

      //删除按键
      var deleteImg = document.createElement("img");
      deleteImg.src = deleteIcon;
      function renderIcon(icon) {
        return function renderIcon(
          ctx,
          left,
          top,
          styleOverride,
          fabricObject
        ) {
          var size = this.cornerSize;
          ctx.save();
          ctx.translate(left, top);
          ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle));
          ctx.drawImage(icon, -size / 2, -size / 2, size, size);
          ctx.restore();
        };
      }
      fabric.Object.prototype.controls.deleteControl = new fabric.Control({
        x: 0.5,
        y: -0.5,
        offsetY: -16,
        offsetX: 16,
        cursorStyle: "pointer",
        mouseUpHandler: deleteObject,
        render: renderIcon(deleteImg),
        cornerSize: 24,
      });

      function deleteObject(eventData, transform) {
        var target = transform.target;
        var canvas = target.canvas;

        canvas.remove(target);
        canvas.requestRenderAll();
      }

      console.log("canvas mounted");
    }
  }, [CanvasRef]);

  function addImage(img_path, left = 0, top = 0) {
    fabric.Image.fromURL(img_path, function (oImg) {
      oImg.left = left;
      oImg.top = top;
      fabricCanvas.current?.add(oImg);
      // oImg.bringToFront();
      fabricCanvas.current?.setActiveObject(oImg);
    });
  }

  function setWidth(width) {
    fabricCanvas.current?.setWidth(width);
  }

  function setHeight(height) {
    fabricCanvas.current?.setHeight(height);
  }

  function exportImage() {
    const selection = fabricCanvas.current?.getActiveObject();

    if (!selection) {
      window.alert("😟 请选择图片");
      return;
    }

    console.log(selection);

    //生成链接
    const dataURL = selection.toDataURL();

    //模拟点击
    const link = document.createElement("a");
    link.download = "canvas.png";
    link.href = dataURL;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  function moveUp() {
    const selection = fabricCanvas.current?.getActiveObject();
    if (!selection) {
      window.alert("😟 请选择图片");
      return;
    }

    fabricCanvas.current?.bringForward(selection);
  }

  function moveBack() {
    const selection = fabricCanvas.current?.getActiveObject();
    if (!selection) {
      window.alert("😟 请选择图片");
      return;
    }

    fabricCanvas.current?.sendBackwards(selection);
  }

  function addText(text) {
    var text = new fabric.Text(text);
    fabricCanvas.current?.add(text);
  }

  function clear() {
    fabricCanvas.current?.clear();
  }

  const fabricCanvasHandler = {
    CanvasRef: CanvasRef,

    setWidth: setWidth,
    setHeight: setHeight,

    addImage: addImage,
    addText: addText,
    exportImage: exportImage,
    clear: clear,

    moveUp: moveUp,
    moveBack: moveBack,
  };
  return fabricCanvasHandler;
}

let text = "";
function QuickAccess() {
  const fcHandler = useContext(fcContext);
  const [open, setOpen] = useState(false);

  return (
    <>
      <Modal
        title="添加文字"
        open={open}
        onCancel={() => {
          setOpen(false);
        }}
        onOk={()=>{
          setOpen(false);
          fcHandler.addText(text)
        }}
      >
        <Input.TextArea
          onChange={(e) => {
            text = e.target.value;
            // console.log(text);
          }}
        />
      </Modal>
      <FloatButton.Group
        trigger="hover"
        style={{ right: 30 }}
        icon={<UpOutlined />}
      >
        <FloatButton
          icon={<FontSizeOutlined />}
          onClick={() => {
            setOpen(true);
          }}
          tooltip="添加文字"
        />
        <FloatButton
          icon={<ArrowUpOutlined />}
          onClick={fcHandler.moveUp}
          tooltip="向上移动"
        />

        <FloatButton
          icon={<ArrowDownOutlined />}
          onClick={fcHandler.moveBack}
          tooltip="向下移动"
        />

        <FloatButton
          icon={<ClearOutlined />}
          onClick={fcHandler.clear}
          tooltip="清空画布"
        />

        <FloatButton
          icon={<SaveOutlined />}
          onClick={fcHandler.exportImage}
          type="primary"
          tooltip="导出图片"
        />
      </FloatButton.Group>
    </>
  );
}

var deleteIcon =
  "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg version='1.1' id='Ebene_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='595.275px' height='595.275px' viewBox='200 215 230 470' xml:space='preserve'%3E%3Ccircle style='fill:%23F44336;' cx='299.76' cy='439.067' r='218.516'/%3E%3Cg%3E%3Crect x='267.162' y='307.978' transform='matrix(0.7071 -0.7071 0.7071 0.7071 -222.6202 340.6915)' style='fill:white;' width='65.545' height='262.18'/%3E%3Crect x='266.988' y='308.153' transform='matrix(0.7071 0.7071 -0.7071 0.7071 398.3889 -83.3116)' style='fill:white;' width='65.544' height='262.179'/%3E%3C/g%3E%3C/svg%3E";

export { useFabricCanvas, fcContext, QuickAccess };
